<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/6/29 0029
// +----------------------------------------------------------------------
// | Description:  
// +----------------------------------------------------------------------

namespace app\admin\controller;


use app\admin\model\AdminUser;
use app\admin\model\AuthGroups;
use app\admin\model\GroupAccess;
use app\admin\validate\CheckGroups;
use app\common\controller\AdminBaseController;
use app\admin\model\AuthRule;
use Jrk\Tool;
use Jrk\Tree;
use think\Exception;
use think\facade\Db;

class AuthGroup extends AdminBaseController
{
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub

        $this->model = new AuthGroups();
    }


    /**
     * @return string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/6/29 0029
     * @describe:添加编辑
     */
    public function addGroups()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            try {
                //验证提交的数据
                $validate = new CheckGroups();
                if (!$validate->check($data)) {
                    return parent::JsonReturn($validate->getError(), 0);
                }
                if (!isset($data['id'])) {
                    $res = AuthGroups::where(['title' => "" . $data['title'] . ""])->find();
                    if ($res) {
                        return parent::JsonReturn($data['title'] . "该名称已存在", 0);
                    }
                }
                $data['rules'] = @implode(",", array_unique($data['rule']));
                unset($data['rule']);
            } catch (Exception $exception) {
                return parent::JsonReturn($exception->getMessage(), 0);
            }
            return $this->model->doAll($data);

        }
        $k=AuthGroups::where("status",1)->select()->toArray();
        $tree = Tree::toFormatTree($k);
        $id = $this->request->param("id/d", 0);//父id
        $info = AuthGroups::find($id);
        $this->assign(compact("info", "id","tree"));
        return $this->fetch("auth_group");
    }


    /**
     * @return string|\think\response\Json
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/30 0030
     * @describe:角色授权
     */
    public function userGroup()
    {
        if (IS_AJAX) {
            $data = $this->request->post();

            try {
                if (!isset($data['uid'])) {
                    $group_access = GroupAccess::where("group_id", "=", $data['group_id'])->delete();
                    if ($group_access) {
                        return parent::JsonReturn("取消授权成功");
                    } else {
                        return parent::JsonReturn("取消授权失败", 0);
                    }
                }
                //获取当前 权限组已经授权的人员ID
                $group_access = GroupAccess::field("uid")->where("group_id", "=", $data['group_id'])->column("uid");
                // dd($group_access);
                if (empty($group_access)) {
                    return $this->addG($data["uid"], $data['group_id']);
                } else {
                    //提交的 授权人员ID
                    $a_uid = [];
                    foreach ($data["uid"] as $k => $v) {
                        $a_uid[] = intval($v);
                    }
                    // 合并两个UID
                    $all = array_merge($group_access, $a_uid);
                    //去除重复的UID
                    $final = array_unique($all);
                    $arr_insert = [];
                    foreach ($final as $k => $v) {
                        //当前传的ID不在表中
                        if (!in_array($v, $group_access)) {
                            $arr_insert[] = ['uid' => $v, 'group_id' => $data['group_id'], 'create_time' => time()];
                        }
                    }
                    // dd($arr_insert);
                    if (empty($arr_insert)) {
                        return parent::JsonReturn("数据暂未修改", 0);
                    } else {
                        $res = Db::name("auth_group_access")->insertAll($arr_insert);
                        if ($res) {
                            return parent::JsonReturn("授权成功");
                        } else {
                            return parent::JsonReturn("授权失败", 0);
                        }
                    }
                }
            } catch (\Exception $exception) {
                return parent::JsonReturn($exception->getMessage(), 0);
            }
        }

        $id = $this->request->param("id/d", 0);//父id
        //
        $group_access = GroupAccess::where("group_id", "=", $id)->select();

        $user = AdminUser::where("status", "=", 1)->where("id", "<>", 1)->select();

        //查询当前已经授权的人员

        if (!empty($user) && !empty($group_access)) {
            foreach ($user as $k => $v) {
                foreach ($group_access as $t => $g) {
                    if ($g['uid'] == $v['id']) {
                        $user[$k]['checked'] = true;
                    }
                }
            }
        }

        $this->assign(compact("id", "user", "group_access"));
        return $this->fetch();
    }


    /**
     * @param $arrs
     * @param $group_id
     * @return \think\response\Json
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/6/30 0030
     * @describe:
     */
    protected function addG($arrs, $group_id)
    {
        $arr = [];
        foreach ($arrs as $k => $v) {
            $arr[] = ['uid' => $v, 'group_id' => $group_id, 'create_time' => time()];
        }
        $res = Db::name("auth_group_access")->insertAll($arr);
        if ($res) {
            return parent::JsonReturn("授权成功");
        } else {
            return parent::JsonReturn("授权失败", 0);
        }
    }


    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/6/29 0029
     * @describe:授权菜单
     */
    public function getRoles()
    {
        if (IS_AJAX) {
            $id = $this->request->param("id/d", 0);
            //新增 权限
            if ($id == 0) {
                $res = AuthRule::menuALL(["status" => 1, 'auth_open' => 1]);
                $list = $this->eachData($res);
            } else {
                $rules = AuthGroups::where("id", "=", $id)->value("rules");
                if (empty($rules)) {
                    $res = AuthRule::menuALL(["status" => 1, 'auth_open' => 1]);
                    $list = $this->eachData($res);
                } else {
                    $all = AuthRule::menuALL(["status" => 1, 'auth_open' => 1]);
                    $ids = @explode(",", $rules);
                    if (!empty($all)) {
                        //先数组添加 查看
                        $lists = $this->eachData($all);
                        foreach ($lists as $k => $v) {
                            if (in_array($v['id_'], $ids)) { //
                                $lists[$k]['checked'] = true; //追加默认选中
                                //$da[$k]['disable']=true; //不可选择
                            }
                        }
                        $list = $lists;
                    } else {
                        $list = $all;
                    }
                }
            }

            return parent::JsonReturn("ok", 1, '', Tree::DeepTree($list, "list"));
        }
    }


    /**
     * @param $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/7/1 0001
     * @describe:
     */
    protected function isChild($id)
    {
        $res = Db::name("auth_rule")->where("pid", $id)->where("type", 1)->find();
        if ($res) {
            return false;
        }
        return true;
    }


    /**
     * @param $list
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/7/1 0001
     * @describe: 循环数组追加查看
     */
    protected function eachData($list)
    {
        if (empty($list)) return [];
        foreach ($list as $k => $v) {
            $ck = $this->isChild($v['id']);
            if ($v['type'] == 1 && $ck) {
                array_push($list, ["id" => (int)Tool::uniqidNumberCode(4), "id_" => $v['id'], "pid" => $v['id'], "name" => $v['name'], 'type' => 2, 'title' => '查看', 'auth_open' => 1, 'status' => 1]);
            }
            $list[$k]['id_'] = $v['id'];
        }
        return $list;
    }


}